import React, { Component } from 'react';
// import PropTypes from "prop-types";
import { connect } from 'dva';
import { Icon, Table, Popconfirm, Button } from 'antd';
import moment from 'moment';
import Authorized, { checkAuthority } from 'utils/Authorized';
import AdminEditForm from 'components/permissionset/mgtname/admineditform';
import RoleEditForm from 'components/permissionset/mgtname/roleeditform';

@connect(state => ({
  global: state.global,
  mgtname: state.mgtname,
}))
export default class Pages extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false, //是否展示新增Modal
      selectedRowKeys: [], // Check here to configure the default column
      loading: false,
      modalType: '',
      formDatas: null,
      roleVisible: false, //是否展示新增Modal
      recordAllRole: {
        checkedKeys: [],
        treeData: [],
      },
      currentId: '', //保存点击事件ID
    };
  }
  componentDidMount() {
    this.getList({ pageNum: 1, pageSize: 10 });
  }

  /**
   * 数据获取
   */
  getList = payload => {
    this.props.dispatch({
      type: 'mgtname/getList',
      payload,
    });
  };

  // 处理列表单选框事件
  handleRowSelectChange = (selectedRowKeys, selectedRows) => {
    this.setState({ selectedRowKeys });
  };

  //批量删除
  handleBathDelete = () => {
    const { dispatch } = this.props;
    const { selectedRowKeys } = this.state;
    dispatch({
      type: 'mgtname/delete',
      payload: { selectedRowKeys },
      callback: res => {
        if (res.code === 200) {
          this.setState({
            selectedRows: [],
            selectedRowKeys: [],
          });
        }
      },
    });
  };

  //关闭新增管理员
  HandleCloseadminModal = () => {
    this.setState({
      visible: false,
    });
  };

  //打开新增管理员
  HandleOpenadminModal = (type, datas) => {
    this.setState({
      visible: true,
      modalType: type,
      currentId: datas.id,
      formDatas: datas || null,
    });
  };

  //新增 编辑管理员
  addManage = values => {
    const { dispatch } = this.props;
    const { modalType, currentId } = this.state;
    if (modalType === 'edit') {
      dispatch({
        type: 'mgtname/edit',
        payload: {
          id: currentId,
          values,
        },
      });
      this.HandleCloseadminModal('edit');
    } else {
      dispatch({
        type: 'mgtname/add',
        payload: values,
      });
      this.HandleCloseadminModal('add');
    }
  };

  // 编辑管理员
  handleModalVisible = record => {
    // 打开编辑框
    this.HandleOpenadminModal('edit', record);
  };

  //翻页按钮
  handlePageChange = (pageNum, pageSize) => {
    this.getList({ pageNum, pageSize });
  };

  //关闭角色Modal
  HandleCloseRoleModal = () => {
    this.setState({
      roleVisible: false,
    });
  };

  /**
   * 获取用户角色分配情况
   */
  HandleOpenRoleModal = record => {
    // 获取编辑数据
    const { dispatch } = this.props;
    dispatch({
      type: 'mgtname/getRoleList',
      payload: record.id,
      callback: response => {
        if (response.code === 200) {
          this.setState({
            currentId: record.id,
            roleVisible: true,
            recordAllRole: response.data,
            formDatas: record || null,
          });
        }
      },
    });
  };

  //角色回调
  addRole = values => {
    const { dispatch } = this.props;
    dispatch({
      type: 'mgtname/editRole',
      payload: {
        values,
        adminId: this.state.currentId,
      },
    });
    this.HandleCloseRoleModal();
  };

  render() {
    const {
      mgtname: { page, loading, visibleDTM },
      global: { departOptions, diseOptions },
    } = this.props;
    const { visible, selectedRowKeys, modalType, formDatas, roleVisible } = this.state;

    const rowSelection = {
      selectedRowKeys,
      onChange: this.handleRowSelectChange,
      getCheckboxProps: record => ({
        disabled: record.disabled,
      }),
    };

    const pagiNation = {
      pageSize: page.pageSize,
      total: page.total,
      current: page.pageNum,
      onChange: this.handlePageChange,
    };

    //表格列定义
    const columns = [
      {
        title: '登录名',
        dataIndex: 'userName',
        key: 'userName',
      },
      {
        title: '手机号',
        dataIndex: 'cellphone',
        key: 'cellphone',
      },
      {
        title: '邮箱',
        dataIndex: 'email',
        key: 'email',
      },
      {
        title: '昵称',
        dataIndex: 'nickName',
        key: 'nickName',
      },
      {
        title: '角色',
        dataIndex: 'roles',
        key: 'role',
        render: (text, record) => {
          return 0 === record.roles.length
            ? '未分配角色'
            : record.roles.map((item, index) => item.name + ' ');
        },
      },
      {
        title: '备注',
        dataIndex: 'remark',
        key: 'remark',
      },
      {
        title: '最近活动时间',
        dataIndex: 'updateDate',
        key: 'updateDate',
        render: val => <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span>,
      },
      {
        title: '操作',
        render: record => (
          <div>
            <span>
              <Authorized authority={() => checkAuthority('admin:update')} noMatch={<div />}>
                <a onClick={() => this.handleModalVisible(record)}>编辑</a>
              </Authorized>
            </span>
            &emsp;&emsp;
            <span>
              <Authorized authority={() => checkAuthority('refAdminRole:add')} noMatch={<div />}>
                <a onClick={() => this.HandleOpenRoleModal(record)}>分配角色</a>
              </Authorized>
            </span>
          </div>
        ),
      },
    ];

    return (
      <>
        <AdminEditForm
          visible={visible}
          modalType={modalType}
          onCancel={this.HandleCloseadminModal}
          onOk={values => this.addManage(values)}
          record={formDatas}
        />
        <RoleEditForm
          visible={roleVisible}
          modalType="multiple"
          onCancel={this.HandleCloseRoleModal}
          onOk={values => this.addRole(values)}
          recordAllRole={this.state.recordAllRole}
          record={formDatas}
        />
        <div>
          <h3 className="head">用户管理</h3>
          <div style={{ padding: ' 10px 20px' }}>
            <Authorized authority={() => checkAuthority('admin:add')} noMatch={<div />}>
              <Button
                type="primary"
                icon="plus"
                onClick={() => this.HandleOpenadminModal('add', {})}
                className="mr10"
              >
                新增
              </Button>
            </Authorized>
            <span>
              <Authorized authority={() => checkAuthority('admin:batchDelete')} noMatch={<div />}>
                {selectedRowKeys.length > 0 && (
                  <Popconfirm
                    title="删除的数据不能恢复，确定要全部删除吗?"
                    onConfirm={this.handleBathDelete}
                    okText="确定"
                    cancelText="取消"
                  >
                    <Button
                      className="ml10"
                      type="primary"
                      disabled={
                        null != selectedRowKeys && selectedRowKeys.length > 0 ? false : true
                      }
                      icon="delete"
                    >
                      {null != selectedRowKeys && selectedRowKeys.length > 1 ? '批量删除' : '删除'}
                    </Button>
                  </Popconfirm>
                )}
              </Authorized>
            </span>
            <Table
              style={{ marginTop: '10px' }}
              rowSelection={rowSelection}
              columns={columns}
              rowKey={record => record.id}
              loading={loading}
              dataSource={page.list}
              pagination={pagiNation}
            />
          </div>
        </div>
      </>
    );
  }
}
